<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="业务类型" prop="auditBusinessType">
        <el-select v-model="queryParams.auditBusinessType" placeholder="请选择审核业务类型" clearable>
          <el-option
            v-for="dict in dict.type.audit_business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:leave:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single || (ids.length === 1 && !isPendingAudit(leaveList.find(item => item.leaveId === ids[0]) || {}))"
          @click="handleUpdate"
          v-hasPermi="['system:leave:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:leave:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:leave:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="业务类型" align="center" prop="auditBusinessType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_business_type" :value="scope.row.auditBusinessType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始日期" align="center" prop="startDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDatetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endDatetime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDatetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_status" :value="scope.row.auditStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="isPendingAudit(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:leave:edit']"
          >修改
          </el-button>
          <el-button
            v-if="isPendingAudit(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:leave:remove']"
          >删除
          </el-button>
          <el-button
            v-if="!isPendingAudit(scope.row)"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改请假对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>  <!-- 宽度可适当调大 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="dialogReadonly">
        <!-- 新增 el-row 包裹 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="业务类型" prop="auditBusinessType">
              <el-select v-model="form.auditBusinessType" placeholder="请选择业务类型">
                <el-option
                  v-for="dict in dict.type.audit_business_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开始日期" prop="startDatetime">
              <el-date-picker clearable
                              v-model="form.startDatetime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束日期" prop="endDatetime">
              <el-date-picker clearable
                              v-model="form.endDatetime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 审核信息表格 -->
      <template v-if="form.leaveId">
        <el-divider content-position="left">审核信息</el-divider>
        <audit-info-table
          :data="auditInfo"
          :node-mode-options="dict.type.audit_mode"
          :audit-status-options="dict.type.audit_status"
          :audit-result-options="dict.type.audit_result"
          :format-fallback="formatAssignees"
          :show-round="true"
          :show-order="true"
          :show-copy-info="true"
          :role-fields="['auditRoleName', 'auditRoleId']"
        />
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="!dialogReadonly" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ dialogReadonly ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listLeave, getLeave, delLeave, addLeave, updateLeave} from "@/api/system/leave"
import AuditInfoTable from "@/components/AuditInfoTable"

export default {
  name: "Leave",
  dicts: ['audit_business_type', 'audit_status', 'audit_mode', 'audit_result'],
  components: {
    AuditInfoTable
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假表格数据
      leaveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        auditBusinessType: null,
        auditStatus: null,
      },
      // 表单参数
      form: {},
      // 审核信息
      auditInfo: [],
      // 对话框只读模式
      dialogReadonly: false,
      // 表单校验
      rules: {
        startDatetime: [
          {required: true, message: "开始时间不能为空", trigger: "blur"}
        ],
        endDatetime: [
          {required: true, message: "结束时间不能为空", trigger: "blur"}
        ],
        auditBusinessType: [
          {required: true, message: "业务类型不能为空", trigger: "change"}
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询请假列表 */
    getList() {
      this.loading = true
      listLeave(this.queryParams).then(response => {
        this.leaveList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        leaveId: null,
        auditBusinessType: null,
        startDatetime: null,
        endDatetime: null,
        auditStatus: null,
        currentAuditNodeId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
      this.auditInfo = []
      this.dialogReadonly = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.leaveId)
      this.single = selection.length !== 1
      // 如果选中的数据中有非待审核状态的，禁用删除按钮
      this.multiple = !selection.length || selection.some(item => !this.isPendingAudit(item))
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加请假"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const leaveId = row.leaveId || this.ids
      getLeave(leaveId).then(response => {
        const resData = response.data || {}
        const auditInfo = Array.isArray(resData.auditInfo) ? resData.auditInfo : []
        const {auditInfo: _ignoredAuditInfo, ...formData} = resData
        this.form = formData
        this.auditInfo = auditInfo
        this.dialogReadonly = false
        this.open = true
        this.title = "修改请假"
      })
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset()
      const leaveId = row.leaveId
      getLeave(leaveId).then(response => {
        const resData = response.data || {}
        const auditInfo = Array.isArray(resData.auditInfo) ? resData.auditInfo : []
        const {auditInfo: _ignoredAuditInfo, ...formData} = resData
        this.form = formData
        this.auditInfo = auditInfo
        this.dialogReadonly = true
        this.open = true
        this.title = "查看详情"
      })
    },
    /** 判断是否为待审核状态（只有待审核状态才能修改和删除） */
    isPendingAudit(row) {
      // 只有待审核(0) 状态才能修改和删除
      return row && row.auditStatus === '0'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitData = {...this.form}
          if (this.form.leaveId != null) {
            updateLeave(submitData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLeave(submitData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const leaveIds = row.leaveId || this.ids
      this.$modal.confirm('是否确认删除请假编号为"' + leaveIds + '"的数据项？').then(function () {
        return delLeave(leaveIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/leave/export', {
        ...this.queryParams
      }, `leave_${new Date().getTime()}.xlsx`)
    },
    /** 格式化审核人员列表 */
    formatAssignees(list) {
      if (!Array.isArray(list) || list.length === 0) {
        return '-'
      }
      const names = list
        .map(item => item && (item.userName || item.userId))
        .filter(item => item !== undefined && item !== null && item !== '')
      return names.length ? names.join('、') : '-'
    }
  }
}
</script>
